package com.whq.mvc.config;

import com.whq.mvc.resp.BusinessException;
import com.whq.mvc.resp.CommonReturnType;
import com.whq.mvc.resp.EmBusinessError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public CommonReturnType doErro(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        ex.printStackTrace();
        Map<String, Object> resp = new HashMap<>();
        if (ex instanceof BusinessException) {
            BusinessException exception = (BusinessException) ex;
            resp.put("errCode", exception.getErrCode());
            resp.put("errMsg", exception.getErrMsg());
        } else {
            resp.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
            resp.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
        }

        return CommonReturnType.create(resp, "fail");
    }
}
